from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import mixins
from rest_framework import generics
from rest_framework import filters
from rest_framework.pagination import PageNumberPagination
from rest_framework import viewsets
from rest_framework_extensions.cache.mixins import CacheResponseMixin  # 缓存 pip install drf-extensions
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle  # 限速

from django_filters.rest_framework import DjangoFilterBackend  # 过滤

from .models import Goods
from .models import GoodsCategory  # 商品类别
from .models import Banner
from .models import HotSearchWords  # 热搜词
from .filters import GoodsFilter  # 自定义过滤器规则
from .serializers import GoodsSerializer, CategorySerializer, BannerSerializer, IndexCategorySerializer, \
    HotWordsSerializer


# 自定义分页类
class GoodsPagination(PageNumberPagination):
    page_size = 10  # 每页显示多少条
    page_query_param = "page"  # 分页查询参数名称
    page_size_query_param = 'page_size'
    max_page_size = 100  # 允许最大请求页面大小数值


class GoodsListViewSet(CacheResponseMixin,viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin):
    """
    CacheResponseMixin缓存，必须放到第一位
    mixins.RetrieveModelMixin商品详情页
    商品列表页，分页，搜索，过滤,排序
    """
    # throttle_classes = (UserRateThrottle, AnonRateThrottle)  # 限速
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination

    # 自定义配置筛选、搜索、排序
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter]
    filter_class = GoodsFilter  # 自定义筛选
    search_fields = ["name", "goods_brief", "goods_desc"]  # 搜索字段配置
    ordering_fields = ["sold_num", "add_time"]  # 排序字段配置

    # 商品点击数+1
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.click_num += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


# 继承mixins.RetrieveModelMixin和路由中的goods_list = GoodsListViewSet.as_view({"get": "list"})即可完成路由命名匹配
# 接口的url直接输入id查看详情：例如：http://127.0.0.1:8000/categorys/1/   查看id=1的分类详细
class CategoryViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin,
                      viewsets.GenericViewSet):
    """
    list:
        商品分类列表数据
    retrieve:
        获取商品分类详情
    """
    queryset = GoodsCategory.objects.all()
    serializer_class = CategorySerializer
    pagination_class = GoodsPagination


class HotSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    获取热搜词列表
    """
    queryset = HotSearchWords.objects.all().order_by("-index")
    serializer_class = HotWordsSerializer


class BannerViewsSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    获取轮播图
    """
    queryset = Banner.objects.all().order_by("-index")  # 倒序
    serializer_class = BannerSerializer


class IndexCategoryViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    首页商品分类数据
    """
    queryset = GoodsCategory.objects.filter(is_tab=True, name__in=["生鲜食品", "酒水饮料"])
    serializer_class = IndexCategorySerializer
